import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { jwtConstants } from '../../shared/constants';

export interface JwtPayload {
  username: string;
  userId: number;
  roles: string; //json字符化
}

@Injectable()
export default class JwtAuthStrategy extends PassportStrategy(Strategy, 'jwt') {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: jwtConstants.secret,
    });
  }

  async validate(payload: JwtPayload, req: any) {
    const { username, userId, roles } = payload;
    // 将解析后的token，挂在req.user上
    req.user = { username, userId, roles };
    return {
      username,
      userId,
      roles,
    };
  }
}
